package com.example.mentalarithmetic;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.widget.Toolbar;

import com.example.question.CreatQandA;
import com.example.question.QandaType;
import com.example.question.QuestionType;
import com.example.question.QuestiontypeEnum;
import com.example.question.Type;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.List;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import top.androidman.SuperButton;

public class ComputeActivity extends BaseActivity {
    //申明控件
    private TextView textView_quote;
    private EditText et_answer;
    private TextView textView_cnt;
    private TextView tv_question;
    private TextView tv_title;
    private SuperButton superButton_submit;
    private SuperButton superButton_next;
    private SuperButton superButton_last;
    private Toolbar toolbar;
    //初始化各个参数
    private int buttonFlag = 0;
    private int cnt = 0;
    private int total;
    private int wrongNum=0;
    private CreatQandA creatQandA;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_compute);
        Intent intent = getIntent();
        String title = intent.getStringExtra("title");
        int imgId = intent.getExtras().getInt("id");

        final String httpUrl = "https://api.tianapi.com/txapi/dictum/index";
        final String httpArg = "key=707776c4c43020987a90c5072414594e&num=1";

        textView_quote = findViewById(R.id.tv_quotes);
        textView_quote.setMovementMethod(ScrollingMovementMethod.getInstance());//设置文本显示框可以上下滑动翻页
        toolbar = findViewById(R.id.toolbar2);
        setSupportActionBar(toolbar);
        toolbar.setTitle(title + "口算");
        textView_cnt = findViewById(R.id.tv_cnt);
        tv_title = findViewById(R.id.tv_title);
        tv_question = findViewById(R.id.tv_question);
        superButton_submit = findViewById(R.id.bt_submit);
        superButton_next = findViewById(R.id.bt_next);
        superButton_last = findViewById(R.id.bt_last);
        et_answer = findViewById(R.id.et_answer);

        superButton_last.setVisibility(View.INVISIBLE);
        superButton_next.setVisibility(View.INVISIBLE);
        et_answer.setVisibility(View.INVISIBLE);
        tv_question.setVisibility(View.INVISIBLE);
        tv_title.setVisibility(View.INVISIBLE);

        superButton_submit.setText("开始");
        //定义题目类型和在所以题目中的占比
        ArrayList<Type> types = new ArrayList<>();
        switch(imgId){
            case R.mipmap.bookssjbshuxuexs1scover:
                types.add(new Type(1, QuestiontypeEnum.TWENTY_SUB));
                types.add(new Type(3, QuestiontypeEnum.TWENTY_ADD_SUB));
                break;
            case R.mipmap.bookssjbshuxuexs1xcover:
                types.add(new Type(1, QuestiontypeEnum.TWENTY_ADD_SUB));
                types.add(new Type(2,QuestiontypeEnum.HUNDRED_ADD));
                types.add(new Type(2,QuestiontypeEnum.HUNDRED_SUB));
                types.add(new Type(1,QuestiontypeEnum.HUNDRED_ADD_SUB));
                break;
            case R.mipmap.bookssjbshuxuexs2scover:

                break;
            case R.mipmap.bookssjbshuxuexs2xcover:
                break;
            case R.mipmap.bookssjbshuxuexs3scover:
                break;
            case R.mipmap.bookssjbshuxuexs3xcover:
                break;
            case R.mipmap.bookssjbshuxuexs4scover:
                break;
            default:
                types.add(new Type(1, QuestiontypeEnum.TWENTY_SUB));
                types.add(new Type(4, QuestiontypeEnum.TWENTY_ADD_SUB));

        }

        //设置题目总数、年级等信息
        QuestionType questionType = new QuestionType(imgId, 30, types);
        //通过创建的题目类型创建题目
        creatQandA = new CreatQandA(questionType);
        creatQandA.start();

        total = creatQandA.getTotal();
        ArrayList<QandaType> qandaTypes = creatQandA.getQandaTypeList();

        superButton_submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                switch (buttonFlag) {
                    case 0:
                        sendRequestWithOkHttp(httpUrl,httpArg);
                        buttonFlag = 1;
                        superButton_submit.setText("提交");
                        creatQandA.start();
                        textView_cnt.setText("算一算:\n" + String.valueOf(cnt + 1) + "/" + String.valueOf(total));
                        tv_question.setText(creatQandA.getQandaTypeList().get(cnt).getQuestion());
                        superButton_last.setVisibility(View.VISIBLE);
                        superButton_next.setVisibility(View.VISIBLE);
                        et_answer.setVisibility(View.VISIBLE);
                        tv_question.setVisibility(View.VISIBLE);
                        tv_title.setVisibility(View.VISIBLE);
                        et_answer.setText("");
                        et_answer.setTextColor(getResources().getColor(R.color.color_text_black));
//                    Log.d("CA1","时间：");
//                    Log.d("CA1",String.valueOf(creatQandA.getQandaTypeList().get(0).getCreateTime().get(Calendar.YEAR)));
                        break;
                    case 1:
                        if(cnt==total-1) {
                            buttonFlag = 2;
                            creatQandA.getQandaTypeList().get(cnt).setAnswerUser(et_answer.getText().toString());
                            superButton_submit.setText("查看错题");
                            et_answer.setVisibility(View.INVISIBLE);
                            superButton_last.setVisibility(View.INVISIBLE);
                            superButton_next.setVisibility(View.INVISIBLE);
//                        tv_question.setVisibility(View.INVISIBLE);
                            tv_title.setVisibility(View.INVISIBLE);
                            textView_cnt.setText("算一算:\n");
                            //写
                            tv_question.setText("");
                            et_answer.setText("");
                            cnt = 0;
                            wrongNum = 0;
                            int i=0;
                            for (QandaType e : creatQandA.getQandaTypeList()) {

                                e.setAnswerTime(Calendar.getInstance());
                                if (!e.getAnswerRight().equals(e.getAnswerUser())) {
                                    Collections.swap(creatQandA.getQandaTypeList(),i,wrongNum);
                                    wrongNum++;

                                }
                                i++;
                            }
                            tv_question.setText("共有题目" + total + "道,\n" + "答对" + (total - wrongNum) + "道," + "答错" + wrongNum + "道。");
                        }else{
                            Toast.makeText(ComputeActivity.this,"请至最后一题处提交！",Toast.LENGTH_SHORT).show();
                        }
                        break;
                    case 2:
                        superButton_submit.setText("重新开始");
                        buttonFlag=0;
                        superButton_last.setVisibility(View.VISIBLE);
                        superButton_next.setVisibility(View.VISIBLE);
                        et_answer.setVisibility(View.VISIBLE);
                        tv_title.setVisibility(View.VISIBLE);
                        tv_question.setVisibility(View.VISIBLE);
                        textView_cnt.setText("对一对:\n" + String.valueOf(cnt + 1) + "/" + String.valueOf(total));
                        tv_question.setText(creatQandA.getQandaTypeList().get(cnt).getQuestion()+creatQandA.getQandaTypeList().get(cnt).getAnswerRight());
                        et_answer.setText(creatQandA.getQandaTypeList().get(cnt).getAnswerUser());
                        if(!creatQandA.getQandaTypeList().get(cnt).getAnswerRight().equals(creatQandA.getQandaTypeList().get(cnt).getAnswerUser())){
                            et_answer.setTextColor(getResources().getColor(R.color.colorRed));
                        }
                        else{
                            et_answer.setTextColor(getResources().getColor(R.color.colorGreen));
                        }
                        break;
                }
            }
        });
        superButton_next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (buttonFlag) {
                    case 0:

                        cnt++;
                        if (cnt == total) {
                            cnt = 0;
                        }
                        if(!creatQandA.getQandaTypeList().get(cnt).getAnswerRight().equals(creatQandA.getQandaTypeList().get(cnt).getAnswerUser())){
                            et_answer.setTextColor(getResources().getColor(R.color.colorRed));
                        }
                        else{
                            et_answer.setTextColor(getResources().getColor(R.color.colorGreen));
                        }
                        tv_question.setText(creatQandA.getQandaTypeList().get(cnt).getQuestion()+creatQandA.getQandaTypeList().get(cnt).getAnswerRight());
                        et_answer.setText(creatQandA.getQandaTypeList().get(cnt).getAnswerUser());
                        textView_cnt.setText("对一对:\n" + String.valueOf(cnt + 1) + "/" + String.valueOf(total));
                        break;
                    case 1:
                        creatQandA.getQandaTypeList().get(cnt).setAnswerUser(et_answer.getText().toString());
                        cnt++;
                        if (cnt == total) {
                            cnt = 0;
                        }
                        tv_question.setText(creatQandA.getQandaTypeList().get(cnt).getQuestion());
                        et_answer.setText(creatQandA.getQandaTypeList().get(cnt).getAnswerUser());
                        textView_cnt.setText("算一算:\n" + String.valueOf(cnt + 1) + "/" + String.valueOf(total));
                        break;

                }

            }
        });
        superButton_last.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (buttonFlag) {
                    case 0:
                        cnt--;
                        if (cnt < 0) {
                            cnt = total - 1;
                        }
                        if(!creatQandA.getQandaTypeList().get(cnt).getAnswerRight().equals(creatQandA.getQandaTypeList().get(cnt).getAnswerUser())){
                            et_answer.setTextColor(getResources().getColor(R.color.colorRed));
                        }
                        else{
                            et_answer.setTextColor(getResources().getColor(R.color.colorGreen));
                        }
                        tv_question.setText(creatQandA.getQandaTypeList().get(cnt).getQuestion()+creatQandA.getQandaTypeList().get(cnt).getAnswerRight());
                        et_answer.setText(creatQandA.getQandaTypeList().get(cnt).getAnswerUser());
                        textView_cnt.setText("对一对:\n" + String.valueOf(cnt + 1) + "/" + String.valueOf(total));
                        break;
                    case 1:
                        creatQandA.getQandaTypeList().get(cnt).setAnswerUser(et_answer.getText().toString());
                        cnt--;
                        if (cnt < 0) {
                            cnt = total - 1;
                        }
                        tv_question.setText(creatQandA.getQandaTypeList().get(cnt).getQuestion());
                        et_answer.setText(creatQandA.getQandaTypeList().get(cnt).getAnswerUser());
                        textView_cnt.setText("算一算:\n" + String.valueOf(cnt + 1) + "/" + String.valueOf(total));
                        break;
                }

            }
        });
    }

    private Newslist parseJSONWithGSON(String jsonData) {
        Gson gson = new Gson();
        QuotesJson quotesJson = gson.fromJson(jsonData, QuotesJson.class);
        String code = quotesJson.getCode();
        Newslist list = new Newslist();
        if (!code.equals("200")) {
            list.setContent("好好学习，天天向上！");
            list.setMrname("毛泽东");
            return list;
        }
        List<Newslist> newslist = quotesJson.getNewslist();
        for (int i = 0; i < newslist.size(); i++) {//解析第二层
            list.setMrname(newslist.get(i).getMrname());
            list.setContent(newslist.get(i).getContent());
        }
        return list;
    }

    private void sendRequestWithOkHttp(String httpUrl, String httpArg) {
        final String Url = httpUrl + "?" + httpArg;
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient client = new OkHttpClient();
                    Request request = new Request.Builder()
                            .url(Url)
                            .build();
                    Response response = client.newCall(request).execute();
                    String responseData = response.body().string();
                    showResponse(parseJSONWithGSON(responseData));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void showResponse(final Newslist response) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                final String quoteText = "学一学名人名言:\n" + response.getContent() + " --" + response.getMrname();
                textView_quote.setText(quoteText);
            }
        });
    }

    //传递给上层活动，用于加载本活动
    public static void actionStart(Context context, String bookName, int bookId) {
        Intent intent = new Intent(context, ComputeActivity.class);
        intent.putExtra("title", bookName);
        intent.putExtra("id", bookId);
        context.startActivity(intent);
    }
}

class Newslist {
    private String content;
    private String mrname;

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public String getMrname() {
        return mrname;
    }

    public void setMrname(String mrname) {
        this.mrname = mrname;
    }
}

class QuotesJson {
    private String code;
    private String msg;
    private List<Newslist> newslist;

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public List<Newslist> getNewslist() {
        return newslist;
    }

    public void setNewslist(List<Newslist> newslist) {
        this.newslist = newslist;
    }
}
